/*
 * Project Name: showtao
 * File Name: ProductController.java
 * Class Name: ProductController
 *
 * Copyright 2014 showtao.com
 *
 * Licensed under the showtao.com
 *
 * http://showtao.com
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.showtao.front.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.showtao.common.controller.BaseController;
import com.showtao.common.dto.ResultDto;
import com.showtao.common.dto.ResultDtoFactory;
import com.showtao.common.dto.widget.DataTablesRequestDto;
import com.showtao.common.dto.widget.DataTablesResponseDto;
import com.showtao.common.util.web.WebUtil;
import com.showtao.common.validation.ValidateException;
import com.showtao.front.domain.ProductCategory;
import com.showtao.front.dto.LabelItemDto;
import com.showtao.front.dto.ProductDto;
import com.showtao.front.dto.upstream.ProductCategorySavingDto;
import com.showtao.front.dto.upstream.ProductSavingDto;
import com.showtao.front.service.ProductService;
import com.showtao.front.service.VehicleService;

/**
 * Class Name: ProductController Description: TODO
 * 
 * @author
 * 
 */
@Controller
public class ProductController extends BaseController {

	@Autowired
	private transient ProductService productService;

	@Autowired
	private transient VehicleService vehicleService;

	@Autowired
	private transient WebUtil webUtil;

	@RequestMapping(value = "/search/tip")
	@ResponseBody
	public ResultDto getSearchTip(
			@RequestParam(value = "q", required = false, defaultValue = "") String keywords,
			@RequestParam(value = "category", required = false, defaultValue = "cover") String category,
			Model model) {
		return ResultDtoFactory.toAck(productService.findSearchTips(keywords,
				category));
	}

	@RequestMapping(value = "/models/{id}/products")
	@ResponseBody
	public ResultDto getProductsByModel(
			@PathVariable("id") Long id,
			@RequestParam(value = "category", required = false, defaultValue = "cover") String category,
			Model model) {
		List<LabelItemDto> labels = vehicleService.getVehicleBreadCrumb(id);
//		Map<String, List<VehicleModelFeature>> map = productService
//				.findFeaturesByModel(id);
		Object[] os = productService.findProductsByModelAndCategory(
				id, category);
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("labels", labels);
		results.put("products", os[0]);
		results.put("map", os[1]);
		return ResultDtoFactory.toAck(results);
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/product_categories", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesResponseDto<ProductCategory> doSearchProductCategories(
			@Valid @RequestBody DataTablesRequestDto requestDto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		// 组装Pageable
		Pageable pageable = requestDto.toPagable();
		// 调用Service接口获得具体的分页数据Page<VehicleBrand>
		Page<ProductCategory> page = productService
				.findProductCategories(pageable);
		// 新建DataTablesResponseDto并以分页数据填充该Dto
		DataTablesResponseDto<ProductCategory> responseDto = new DataTablesResponseDto<ProductCategory>();
		return responseDto.populateFromPage(page, requestDto.getDraw());
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/product_category", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto doSaveProductCategory(
			@Valid @RequestBody ProductCategorySavingDto dto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		productService.saveProductCategory(dto);
		return ResultDtoFactory.toAck("产品类型创建成功");
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/product_category/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public ResultDto doDeleteProductCategory(@PathVariable("id") Long id) throws Exception {
		productService.deleteProductCategory(id);
		return ResultDtoFactory.toAck("产品类型删除成功");
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/products", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesResponseDto<ProductDto> doSearchProducts(
			@Valid @RequestBody DataTablesRequestDto requestDto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		// 组装Pageable
		Pageable pageable = requestDto.toPagable();
		// 调用Service接口获得具体的分页数据Page<VehicleBrand>
		Page<ProductDto> page = productService.findProducts(pageable);
		// 新建DataTablesResponseDto并以分页数据填充该Dto
		DataTablesResponseDto<ProductDto> responseDto = new DataTablesResponseDto<ProductDto>();
		return responseDto.populateFromPage(page, requestDto.getDraw());
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/product", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto doSaveProduct(@Valid @RequestBody ProductSavingDto dto,
			BindingResult result) throws Exception {
		// 判断是否有验证错误
		if (result.hasErrors()) {
			throw new ValidateException(result);
		}
		productService.saveProduct(dto);
		return ResultDtoFactory.toAck("产品创建成功");
	}

	@RequiresPermissions (value={"product_admin"})
	@RequestMapping(value = "/admin/product/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public ResultDto doDeleteProduct(@PathVariable("id") Long id) throws Exception {
		productService.deleteProduct(id);
		return ResultDtoFactory.toAck("产品删除成功");
	}
	
	@RequestMapping(value = "mobile/selection/product")
	public String product(Model model, String productCode, Long modelId, String modelName, String category) throws Exception {
		/*
		Product product = new Product();
		product.setCode(productCode);
		product.setDismountingNotes("这是测试的note");
		Resource resource = new Resource();
		resource.setResId("http://amui.qiniudn.com/bw-2014-06-19.jpg?imageView2/0/w/600");
		product.setDismountingPic(resource);
		*/
		productCode = URLDecoder.decode(productCode,"UTF-8");
		model.addAttribute("product", productService.getProductByCode(productCode));
		model.addAttribute("modelId", modelId);
		model.addAttribute("modelName", URLDecoder.decode(modelName,"UTF-8"));
		model.addAttribute("category", URLDecoder.decode(category,"UTF-8"));
		return "product/mobile_product";
	}
	
	
	@RequestMapping(value = "mobile/selection/products")
	public String products(Model model, Long modelId, String modelName, String category) throws Exception {
		model.addAttribute("modelId", modelId);
		model.addAttribute("modelName", URLDecoder.decode(modelName,"UTF-8"));
		model.addAttribute("category", category);
		return "product/mobile_product_list";
	}
	


}
